# -*- coding: utf-8 -*-
# @Time    : 2025/6/27 12:29
# @Author  : wsxzy98@outlook.com
# @File    : account_move.py
# @Software: VScode

from odoo import models, fields, api

class AccountMove(models.Model):
    _inherit = 'account.move'

    customer_reference = fields.Char(string='客户参考号')

    @api.onchange('invoice_origin')
    def _onchange_invoice_origin_set_customer_reference(self):
        """
        每当 invoice_origin 变动时，自动同步销售单的 customer_reference
        """
        if self.invoice_origin:
            sale = self.env['sale.order'].search([('name', '=', self.invoice_origin)], limit=1)
            if sale:
                self.customer_reference = sale.customer_reference
            else:
                self.customer_reference = False
        else:
            self.customer_reference = False

    @api.model_create_multi
    def create(self, vals_list):
        """
        创建发票时自动同步销售单的 customer_reference
        """
        for vals in vals_list:
            # 如果传了 invoice_origin 并且没传 customer_reference，则自动同步
            if vals.get('invoice_origin') and not vals.get('customer_reference'):
                sale = self.env['sale.order'].search([('name', '=', vals['invoice_origin'])], limit=1)
                if sale:
                    vals['customer_reference'] = sale.customer_reference
        return super(AccountMove, self).create(vals_list)

    def write(self, vals):
        """
        写入/保存时自动同步
        """
        res = super(AccountMove, self).write(vals)
        # 如果 invoice_origin 被更改或明确要求同步
        if 'invoice_origin' in vals or 'customer_reference' not in vals:
            for rec in self:
                if rec.invoice_origin:
                    sale = self.env['sale.order'].search([('name', '=', rec.invoice_origin)], limit=1)
                    if sale:
                        rec.customer_reference = sale.customer_reference
                    else:
                        rec.customer_reference = False
                else:
                    rec.customer_reference = False
        return res
